<template>
	<div v-show="loadingShow">
		<loading></loading>
	</div>
	<div v-else>
		<div class="card-service-choose">
			<detaile-choose-info typename="ture"></detaile-choose-info>
			<div class="title">
				<div class="left">服务项目</div>
				<div class="right"><i class="sf-tips"></i><a v-link="{path: '/useexplain'}">使用规则</a></div>
			</div>
			<div class="service-main">
				<ul class="service-list">
					<li v-for='item in canChooseList'>
						<div class="left">{{item.serviceName}}</div>
						<div class="right">
							<div>
								<input type="checkbox" @click="selectServer(item.serviceNo,$index,$event)" :id='item.serviceNo' name="radio-1-set" class="regular-radio">
								<label :for='item.serviceNo'><div v-bind:class="{'icon-checked':item.thisChecked}" class="iconfont"></div></label>
							</div>
						</div>
					</li>
					<li v-for='item in infiniteList'>
						<div class="left">{{item.serviceName}}</div>
						<div class="right">
							<div  class="infinite">
								无需下单<br/>
								到店直接服务
							</div>
						</div>
					</li>
					<li v-for='item in zeroList'>
						<div class="left">{{item.serviceName}}</div>
						<div class="right">
							<div   class="infinite">
								剩余0次
							</div>
							
						</div>
					</li>
				</ul>
			</div>
			<a ca="P_用卡下单$选择用卡服务" v-on:click="subMyCardData" class="buy-btn" v-bind:class="{'lock-btn': btnType}">去下单</a>
		</div>
	</div>
</template>
<script>
	import useExplain from '../use-explain';
	import detaileChooseInfo from '../details/detaile-choose-info';
	
	import common from '../../utils/common.js';
	import {Toast,MessageBox} from 'mint-ui';
	import loading from '../common/loading';
	const router = new common.VueRouter();
	
	export default {
		data() {
				return {
					cardSkuId:'',
					getCarInfo:'', //获取车型信息
					getStoreInfo:'', //获取门店信息
					cardserverFlag:false, //选择服务用的标识
					cacheCardInfo:{},  //缓存已选服务信息
					cardInfo:[],
					cardSkuCode:'',
					canChooseList:[],//可选择的服务数据（有限次数）
					infiniteList:[],//不可选择的服务数据（无限次数）
					zeroList:[],//不可选择的服务数据（剩余0次数）
					cacheSeverLocalStorage:{
						serverLength:0
					},//已选择服务项的信息对象，缓存至localStorage
					serviceNo: '',
					btnType:true,
					skuCodeList:[],
					checked:false,
					loadingShow:true
				}
		},
		components: {
			loading
		},
		route:{
			data(){

				common.setTitle('选择服务');  // 设置title

				var _this = this,thisCardData,thisCardServer;
			
				// 商店请求
			    this.$http.post(common.isdev()+'/spu/getSelectedElementInfo.htm',{

			    	targetJumpUrl:window.location.href,
			    	ssCodes:sessionStorage.getItem("cardServerCodeList")

			    }).then(function (data) {

			    		var data = typeof data.data === 'object' ? data.data : JSON.parse(data.data);
						if ( data.result === 0 ) {
							
							common.Toast("请求错误,请刷新页面");
							
						}else if(data.result === 1){

							thisCardData = JSON.parse(localStorage.thisCardData);
			    			thisCardServer = JSON.parse(localStorage.thisCardServer);

							if ( data.obj && typeof data.obj === 'object' ) {
								// 门店信息
								if ( data.obj.storeInfo && typeof data.obj.storeInfo === 'object' ) {
									_this.getStoreInfo = data.obj.storeInfo;
								}
								// 车辆信息
								if ( data.obj.carInfo && typeof data.obj.carInfo === 'object' ) {
									_this.getCarInfo = data.obj.carInfo;
								}
							}

							// 发送到子组件
							_this.$broadcast('initStoreData', _this.getStoreInfo, _this.getCarInfo);

		                    var detaileChooseInfo = {
		                        carRelation:true,
		                        type:'useCard'
		                    }
		                    _this.$broadcast('chooseInfoDataEvent', detaileChooseInfo);
							_this.canChooseList = [];
							_this.loadingShow = false;
							//数据分类 
							for(var i = 0; i < thisCardServer.cardItemVo.length; i++){

								thisCardServer.cardItemVo[i].thisChecked = false;
								if(thisCardServer.cardItemVo[i].isCanOnlineOpenOrder){ //有次数限制
									if(thisCardServer.cardItemVo[i].remainServiceTimes != 0){
										_this.canChooseList.push(thisCardServer.cardItemVo[i]);
									}else{
										_this.zeroList.push(thisCardServer.cardItemVo[i]);
									}
								}else{
									_this.infiniteList.push(thisCardServer.cardItemVo[i]);
								}
							}
						//验证已经选择的服务
						if(sessionStorage.cacheSeverLocalStorage){

							this.loadPageCheckeSelect();
						}
						


						}else if(data.result === -99){
							common.goLogin();
						}else if(data.result === -100){
							window.location.href = '//' + window.location.hostname+ data.obj;
						}
						
						(new Analytics).scan();//打点CA绑定数据
						
			    }, function ( error ) {

			    	console.log(error);
					common.Toast(error.data);
						
				});

			}
		},
		components: {
			useExplain,detaileChooseInfo
		},
		methods: {

			loadPageCheckeSelect:function(){
				var serverSkuList = [];

				this.cacheSeverLocalStorage = JSON.parse(sessionStorage.cacheSeverLocalStorage);

				for(var item in this.cacheSeverLocalStorage){

					if(typeof(this.cacheSeverLocalStorage[item]) === 'object'){

						for(var j = 0; j < this.canChooseList.length; j++){

							if(this.canChooseList[j].serviceNo == this.cacheSeverLocalStorage[item].serviceNo){
								this.canChooseList[j].thisChecked = true;
							}

						}
					}

				}

				for(var skuItem in this.cacheSeverLocalStorage){//获取服务SKUCODE
					if(skuItem == 'serverLength'){
						continue;
					}else{
						serverSkuList.push({"code":this.cacheSeverLocalStorage[skuItem].skuCode});
					}
					
				}
				this.skuCodeList = serverSkuList;
				this.$set('this.canChooseList',this.canChooseList);
				this.checkeSelect();
			},
			selectServer:function(id,index, event){

				var serverSkuList = [],canChooseData = this.canChooseList

				for(var i = 0; i < canChooseData.length; i++){

					if(i == index){

						canChooseData[i].thisChecked = !canChooseData[i].thisChecked;
						
					}

				}

				this.$set('this.canChooseList',canChooseData);

				//console.log(canChooseData);
				if(this.canChooseList[index].thisChecked){
					this.cacheCardInfo['skuCode'+id] = this.canChooseList[index].serviceNo;
					this.cacheSeverLocalStorage['skuCode'+id] = this.canChooseList[index];
					this.cacheSeverLocalStorage.serverLength++;

				}else{
					//console.log('skuCode'+id);
					delete this.cacheCardInfo['skuCode'+id];
					delete this.cacheSeverLocalStorage['skuCode'+id];
					this.cacheSeverLocalStorage.serverLength--;
					
				}

				this.checkeSelect();//验证是否有选择至少一个服务，如果没有则点击去下单按钮失效

				for(var item in this.cacheSeverLocalStorage){//获取服务SKUCODE
					if(item == 'serverLength'){
						continue;
					}else{
						serverSkuList.push({"code":this.cacheSeverLocalStorage[item].skuCode});
					}
					
				}
				this.skuCodeList = serverSkuList;

				sessionStorage.cacheSeverLocalStorage = JSON.stringify(this.cacheSeverLocalStorage);
				localStorage.getCarInfo = JSON.stringify(this.getCarInfo.carName);
				localStorage.getStoreInfo = this.getStoreInfo.storeName;

			},
			checkeSelect:function(){

				if(this.cacheSeverLocalStorage.serverLength > 0){
					this.btnType = false;
				}else{
					this.btnType = true;
				}

			},
			subMyCardData:function(){

				if(this.btnType){
					return false;
				}

				// 数据校验
				var ShoppingCartVo = {
					"productList": this.skuCodeList,
					"storeInfo": {'partnerCode':this.getStoreInfo.partnerCode}
				}

				if(this.getCarInfo.carName){
					ShoppingCartVo.carModelInfo = {carName:this.getCarInfo.carName};
				}

				if(this.getCarInfo.carName == '' || this.getCarInfo.carName == null || this.getCarInfo.carName == 'undefined'){
					Toast('请先选择服务车型');
					return false;

				}

				if(this.getStoreInfo.storeName == '' || this.getStoreInfo.storeName == null || this.getStoreInfo.storeName == 'undefined'){

					Toast('请选择服务门店');
					return false;

				}

				this.$http.post(common.isdev() + '/detail/checkMdse.htm', {
					shoppingCartVo: JSON.stringify(ShoppingCartVo)
				}).then(function ( d ) {

					var resData = typeof d.body === 'object' ? d.body : JSON.parse(d.body);
					
					if ( resData.result == 0 ){

						var cardServerData = JSON.parse(localStorage.thisCardServer).cardItemVo;

						/*switch (resData.errorCode){
							case '0001':
							  Toast('当前服务商品库存不足');
							  break;
							case '0003':
							  Toast('当前服务商品暂不可售');
							  break;
							case '0002':
							  Toast('当前服务商品暂不可售');
							  break;
							case '0060':
							  Toast('商品S码为空');
							  break;
							case '0062':
							  Toast('服务车辆信息不存在');
								break;
							case '0063':
							  Toast('商品强弱关联字段为null');
							  break;
						}*/
						if(resData.skuCode != 'null' || resData.skuCode != null){
							for(var i = 0; i < cardServerData.length; i++){
								if(cardServerData[i].skuCode == resData.skuCode){
									if(resData.errorCode == '0004'){
										Toast('所选门店不支持「'+cardServerData[i].serviceName+'」服务，请重新选择');
										return false;
									}else{
										Toast('所选服务「'+cardServerData[i].serviceName+'」暂不可用');
										return false;
									}
								}
							}
						}else{
							Toast(resData.msg);
						}
						//console.log(resData.skuCode);
						
					} else if ( resData.result == 1 ) {
						// 验证通过
						if(!this.btnType){
							sessionStorage.cardTemplateNo = this.$route.params.cardTemplateNo;
		              		this.$route.router.go({name:'cardconfirmorder',params:{cardTemplateNo:this.$route.params.cardTemplateNo}});
						}
					} else if(resData.result == -99){
						common.goLogin();
					}
					
				}, function ( err ) {
					Toast(err);
				});
				
			}
		}
			
	};
	
	router.map({
		'/use-explain': {
		    component: useExplain
		 }
	})
</script>
<style lang="scss" scoped>
	@import "../../assets/css/_functions.scss";
	@import "../../assets/css/_variables.scss";
	
	.card-service-choose {
		font-size: rem(14);
		color: #333;
		.choose-info{
			padding-left: rem(14);
			background: #fff;
			margin-top: rem(16);
			font-size: rem(14);
			color: #333;
			.choose-info-item{
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: rem(375);
				height: rem(44);
				border-bottom: 1px solid #eee;
				.left{
					
				}
				.right{
					padding-right: rem(20);
					span{
						color: #c7c7cc;
						font-size: rem(14);
					}

				}
			}
		}
		.title{
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: rem(375);
				height: rem(44);
				border-bottom: 1px solid #dedede;
				background: #fff;
				margin-top: rem(16);
				font-size: rem(14);
				color: #333;
				padding-left: rem(20);
				padding-right: rem(14);
				.right{
					font-size: rem(13);
					color: #999;
					a{
						color:#afafaf;
					}
				}
				.sf-tips{
					display:inline-block;
					vertical-align: middle;
					margin-right:rem(3);
				}
		}
		.service-main{
			max-height: 40rem;
    		overflow-y: auto;
    		padding-bottom:1.5rem;
		}
		.service-list{
			padding-left: rem(20);
			background: #fff;
			li{
				
				display: flex;
				align-items: center;
				width: 100%;
				height: rem(44);
				border-bottom: 1px solid #dedede;
				position: relative;
				justify-content: space-between;
			}
			li:last-child{
				border-bottom:0;
			}
			.right{
				
				label{
					position: absolute;
					height: 100%;
					width: 100%;
					border-radius: 0;
					top: 0;
					left: 0;
					display: flex;
					align-items: center;
					border: none;
					justify-content: flex-end;
					
				}
				.infinite{
					font-size: rem(13);
					color: #a2a2a2;
					margin-right: rem(14);
					text-align: right;
				}
				
				
			}
		}
		.buy-btn{
			position: fixed;
			width: 100%;
			height: rem(48);
			background: #ff6600;
			bottom: 0;
			left: 0;
			text-align: center;
			color: #fff;
			line-height: rem(48);
			font-size: rem(18);
		}
		.lock-btn{
			background-color:#a3a3a3;
		}
	}
	.regular-radio {
		display: block;
		width:0px;
		height: 0px;
		visibility: hidden;
	}
	

	.regular-radio+ label>div {
		width: rem(20);
		height: rem(20);
		line-height: rem(20);
		text-align: center;
		border-radius: 100%;
		border: 1px solid $_999;
		margin-right: rem(14);
		color: #fff;
	}
	
	.regular-radio + label .icon-checked {
		border: 1px solid $blue;
		background: $blue;
		width: rem(20);
		height: rem(20);
		line-height: rem(20);
		text-align: center;
		border-radius: 100%;
	}
</style>